/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.marcelo.agro.core;

import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.SwingWorker;

/**
 *
 * @author marcelo
 */
public abstract class ComboEnBackground<T> extends SwingWorker<DefaultComboBoxModel<T>, T>{

    private JComboBox<T> comboAModificar;
    private DefaultComboBoxModel<T> dcbm;
    private Boolean addEmpty =false;
    private Object defaultItem;
    
    public abstract List<T> getDatos();
    
    @Override
    protected DefaultComboBoxModel<T> doInBackground() throws Exception {
        
        DefaultComboBoxModel cbm = new DefaultComboBoxModel();
        if (addEmpty) {
          cbm.addElement("---Seleccione---");
        }
        for (T datos : getDatos()) {
               cbm.addElement(datos);
        }
        return cbm;
    }

    @Override
    protected void done() {
        try{
            dcbm=get(); 
            if (defaultItem != null){
//                comboAModificar.setSelectedItem(defaultItem);
                dcbm.setSelectedItem(defaultItem);
            }
            comboAModificar.setModel(dcbm);
        }
        catch (Exception ignore){
           String causa = ignore.getMessage();
           
        }
    }
    
    public ComboEnBackground(JComboBox cb){
        comboAModificar = cb;
    }
    public ComboEnBackground(JComboBox cb, Boolean addEmpty){
        comboAModificar = cb;
        if (addEmpty != null){ 
            this.addEmpty = addEmpty;
        }
    }
    
    public ComboEnBackground(JComboBox cb, Boolean addEmpty, Object defaultItem){
        comboAModificar = cb;
        if (addEmpty != null){ 
            this.addEmpty = addEmpty;
        }
        this.defaultItem = defaultItem;
    }
    
        
}
